package com.gitee.zycra.config;

import com.gitee.zycra.model.GeneratorConfig;
import org.apache.maven.plugin.MojoFailureException;

import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author zycra
 */
public final class ConfigLoader {

    private ConfigLoader() {
    }

    private static final String SEPARATOR = "/";

    public static GeneratorConfig loanConfig(String propertiesFilePath) throws MojoFailureException {
        Properties properties = new Properties();
        try (FileInputStream in = new FileInputStream(propertiesFilePath)) {
            properties.load(in);
        } catch (Exception e) {
            throw new MojoFailureException("读取配置异常", e);
        }
        return new GeneratorConfig()
                .setUrl(properties.getProperty("jdbc.url"))
                .setUsername(properties.getProperty("jdbc.username"))
                .setPassword(properties.getProperty("jdbc.password"))
                .setDatabase(properties.getProperty("config.database"))
                .setModelPath(addSeparator(properties.getProperty("config.modelPath")))
                .setMapperXmlPath(addSeparator(properties.getProperty("config.mapperXmlPath")))
                .setMapperInterfacePath(addSeparator(properties.getProperty("config.mapperInterfacePath")))
                .setInsertIgnoreList((Arrays.asList(properties.getProperty("config.insertIgnoreList").split(","))))
                .setTableList(Arrays.asList(properties.getProperty("config.tableList").split(",")));
    }

    private static String addSeparator(String path) {
        if (!path.startsWith(SEPARATOR)) {
            path = SEPARATOR + path;
        }
        if (!path.endsWith(SEPARATOR)) {
            path = path + SEPARATOR;
        }
        return path;
    }
}
